/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package it.nyquistmeteocal.boundary;

import it.nyquistmeteocal.entity.Event;
import static java.lang.String.format;
import java.security.Principal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import static java.util.Collections.list;
import java.util.Iterator;

/**
 *
 * @author gatb27
 */
@Stateless
public class EventManager {

    @PersistenceContext
    public EntityManager em;

    @Inject
    Principal principal;

    private static final long serialVersionUID = 1L;

    @EJB
    private UserManager um;
    @EJB
    private NotificationManager nm;

    private String sqlQuery;
    private String LogUser = "prova";

    public void saveEvent(Event event) {
        em.persist(event);
    }

    public void deleteEvent(Event event) {
        Event etbr = em.getReference(Event.class, event.getId());
        em.remove(etbr);
    }

    public void updateEvent(Event event) {
        em.merge(event);
    }

    public List<Event> getEvents() {
        ResultSet rs = null;
        PreparedStatement pst = null;
        Connection con = getConnection();

        System.out.println("value of LogUser before the get:   " + LogUser);
        LogUser = um.getLoggedUser().getEmail();
        System.out.println("value of LogUser after the get:   " + LogUser);

        sqlQuery = "SELECT event.eventname, event.place, event.eventdate, "
                + "event.eventtype, event.visibility, event.creator, event.id, "
                + "event.city, event.weather, event.timestart, event.timefinish "
                + "FROM event, calendarevents "
                + "WHERE event.id=calendarevents.eventid AND calendarevents.useremail=?";

        /*String sqlQuery = "Select name, place, eventdate, type, visibility, creator from event";*/
        List<Event> records = new ArrayList<Event>();
        try {

            pst = con.prepareStatement(sqlQuery);
            pst.setString(1, LogUser);
            pst.execute();
            rs = pst.getResultSet();

            while (rs.next()) {
                Event event = new Event();
                event.setEventname(rs.getString(1));
                event.setPlace(rs.getString(2));
                event.setEventdate(rs.getString(3));
                event.setEventtype(rs.getString(4));
                event.setVisibility(rs.getString(5));
                event.setCreator(rs.getString(6));
                event.setId(rs.getInt(7));
                event.setCity(rs.getString(8));
                event.setWeather(rs.getString(9));
                event.setTimestart(rs.getInt(10));
                event.setTimefinish(rs.getInt(11));
                records.add(event);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return records;

    }

    public List<Event> getEventsSearch(String email) {
        ResultSet rs = null;
        PreparedStatement pst = null;
        Connection con = getConnection();

        sqlQuery = "SELECT event.eventname, event.place, event.eventdate, "
                + "event.eventtype, event.visibility, event.creator, event.id, "
                + "event.city, event.weather, event.timestart, event.timefinish "
                + "FROM event, calendarevents "
                + "WHERE event.id=calendarevents.eventid AND calendarevents.useremail=? "
                + "AND event.visibility='Public'";

        

        List<Event> records = new ArrayList<Event>();
        try {

            pst = con.prepareStatement(sqlQuery);
            pst.setString(1, email);
            pst.execute();
            rs = pst.getResultSet();

            while (rs.next()) {
                Event event = new Event();
                event.setEventname(rs.getString(1));
                event.setPlace(rs.getString(2));
                event.setEventdate(rs.getString(3));
                event.setEventtype(rs.getString(4));
                event.setVisibility(rs.getString(5));
                event.setCreator(rs.getString(6));
                event.setId(rs.getInt(7));
                event.setCity(rs.getString(8));
                event.setWeather(rs.getString(9));
                event.setTimestart(rs.getInt(10));
                event.setTimefinish(rs.getInt(11));
                records.add(event);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        

        return records;

    }

    public List<Event> getBadEvents() {
        ResultSet rs = null;
        PreparedStatement pst = null;
        Connection con = getConnection();

        sqlQuery = "SELECT * "
                + "FROM event "
                + "WHERE weather='Rain' AND eventtype='Outdoor'";

        /*String sqlQuery = "Select name, place, eventdate, type, visibility, creator from event";*/
        List<Event> records = new ArrayList<Event>();
        try {

            pst = con.prepareStatement(sqlQuery);
            pst.execute();
            rs = pst.getResultSet();

            while (rs.next()) {
                Event event = new Event();

                event.setId(rs.getInt("id"));
                event.setEventname(rs.getString("eventname"));
                event.setCity(rs.getString("city"));
                event.setPlace(rs.getString("place"));
                event.setEventdate(rs.getString("eventdate"));
                event.setEventtype(rs.getString("eventtype"));
                event.setVisibility(rs.getString("visibility"));
                event.setCreator(rs.getString("creator"));
                event.setWeather(rs.getString("weather"));
                event.setTimestart(rs.getInt("timestart"));
                event.setTimefinish(rs.getInt("timefinish"));
                records.add(event);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return records;

    }

    
    public List<Event> getTomorrowRainyEvents() {

        List<Event> tmrEvents = getBadEvents();
        Integer count = tmrEvents.size();
        int i;

        SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
        Date d1 = null;
        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();
        cal2.add(Calendar.DAY_OF_YEAR, 1);

        for (Iterator<Event> iter0 = tmrEvents.listIterator(); iter0.hasNext();) {
            Event current0 = iter0.next();
            Integer id = current0.getId();
            List<Integer> notification = nm.getNotification2();
            Boolean value = notification.contains(id);
            if (value) {
                iter0.remove();
            }
        }

        try {
            for (Iterator<Event> iter = tmrEvents.listIterator(); iter.hasNext();) {
                Event current = iter.next();
                d1 = format.parse(current.getEventdate());
                cal1.setTime(d1);
                boolean sameDay = cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)
                        && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR);
                if (sameDay == false) {
                    iter.remove();
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return tmrEvents;
    }

    public List<Event> getBadWeatherEvents() {

        List<Event> badEvents = getBadEvents();
        Integer count = badEvents.size();
        int i;

        SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
        Date d1 = null;
        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();
        cal2.add(Calendar.DAY_OF_YEAR, 3);

        for (Iterator<Event> iter0 = badEvents.listIterator(); iter0.hasNext();) {
            Event current0 = iter0.next();
            Integer id = current0.getId();
            List<Integer> notification = nm.getNotification1();
            Boolean value = notification.contains(id);
            if (value) {
                iter0.remove();
            }
        }

        try {
            for (Iterator<Event> iter = badEvents.listIterator(); iter.hasNext();) {
                Event current = iter.next();
                d1 = format.parse(current.getEventdate());
                cal1.setTime(d1);
                boolean sameDay = cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)
                        && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR);
                if (sameDay == false) {
                    iter.remove();
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return badEvents;
    }

    public Connection getConnection() {
        Connection con = null;

        String url = "jdbc:mysql://localhost:3306/nyreg";
        String user = "monty";
        String password = "some_pass";
        try {
            con = DriverManager.getConnection(url, user, password);
            System.out.println("Connection completed. ");
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
        } finally {
        }
        return con;
    }

    public List<Event> getEvents2(Integer usernotificationid) {
        ResultSet rs = null;
        PreparedStatement pst = null;
        Connection con = getConnection();

        System.out.println("USERNOTIFICATION ID @@@@@@ " + usernotificationid + " @@@@@@@@");

        //LogUser = um.getLoggedUser().getEmail();
        sqlQuery = "SELECT event.eventname, event.place, event.eventdate, "
                + "event.eventtype, event.visibility, event.creator, event.id, "
                + "event.city, event.weather, event.timestart, event.timefinish "
                + "FROM usernotification, notification, event "
                + "WHERE notification.id=? "
                + "AND usernotification.notificationid=notification.id "
                + "AND notification.eventid=event.id";

        /*String sqlQuery = "Select name, place, eventdate, type, visibility, creator from event";*/
        List<Event> records = new ArrayList<Event>();
        try {

            pst = con.prepareStatement(sqlQuery);
            pst.setInt(1, usernotificationid);
            pst.execute();
            rs = pst.getResultSet();

            while (rs.next()) {
                Event event = new Event();
                event.setEventname(rs.getString(1));
                event.setPlace(rs.getString(2));
                event.setEventdate(rs.getString(3));
                event.setEventtype(rs.getString(4));
                event.setVisibility(rs.getString(5));
                event.setCreator(rs.getString(6));
                event.setId(rs.getInt(7));
                event.setCity(rs.getString(8));
                event.setWeather(rs.getString(9));
                event.setTimestart(rs.getInt(10));
                event.setTimefinish(rs.getInt(11));
                records.add(event);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return records;

    }

}
